package com.easylinkin.linkappapi.common.utils.message;

import cn.hutool.core.collection.CollectionUtil;
import cn.jiguang.common.ClientConfig;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosAlert;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.alibaba.fastjson.JSON;
import com.easylinkin.linkappapi.common.utils.message.entity.AppSendMessage;
import com.easylinkin.linkappapi.security.entity.LinkappUser;
import com.easylinkin.linkappapi.security.service.LinkappUserService;
import com.easylinkin.linkappapi.tenant.entity.LinkappTenant;
import com.easylinkin.linkappapi.tenant.sevice.LinkappTenantService;
import com.google.gson.JsonObject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class AppSendMessageUtil {

  private static final Logger LOGGER = LoggerFactory.getLogger(AppSendMessageUtil.class);

  @Value("${jiguangpush.appkey}")
  private String appkey;

  @Value("${jiguangpush.master_secret}")
  private String masterSecret;

  @Value("${jiguangpush.apns_production:false}")
  private Boolean apnsProduction;

  @Autowired
  private LinkappUserService userService;

  @Autowired
  private LinkappTenantService linkappTenantService;

  @Async
  public void sendAppMessage(AppSendMessage appSendMessage) {
    LOGGER.info("极光推送 请求参数：【{}】", JSON.toJSONString(appSendMessage));
    try {
      //获取手机号对应的极光推送的id
      if(StringUtils.isBlank(appSendMessage.getPhone())){
        LOGGER.error("极光推送失败，推送参数缺少手机号");
        return;
      }
      if(StringUtils.isBlank(appSendMessage.getTenantId())){
        LOGGER.error("极光推送失败，推送参数缺少租户信息");
        return;
      }
      List<LinkappUser> linkappUsers = userService.findByPhone(appSendMessage.getPhone());
      LinkappTenant tenant = linkappTenantService.getOneById(appSendMessage.getTenantId());
      if(CollectionUtil.isNotEmpty(linkappUsers)&&null != tenant){
        LinkappUser linkappUser = linkappUsers.get(0);
        String registrationId = linkappUser.getRegistrationId();
        if(StringUtils.isNotEmpty(tenant.getProjectId())){
          appSendMessage.setProjectId(Long.parseLong(tenant.getProjectId()));
        }
        sendMessage(registrationId,appSendMessage);
      }
    }catch (Exception e){
      LOGGER.error("极光推送失败，推送的实体内容为:"+appSendMessage,e.getMessage());
    }
  }

  @SneakyThrows
  private void sendMessage(String registrationId, AppSendMessage appSendMessage) {
    ClientConfig clientConfig = ClientConfig.getInstance();
    clientConfig.setApnsProduction(apnsProduction);
    final JPushClient jpushClient = new JPushClient(masterSecret, appkey, null, clientConfig);
    final PushPayload payload = buildPushObject_android_and_ios(registrationId,appSendMessage);
    PushResult result = jpushClient.sendPush(payload);
    LOGGER.info(appSendMessage+"发送结果为："+result);
  }

  public static PushPayload buildPushObject_android_and_ios(String registrationId,AppSendMessage appSendMessage) {
    Map<String, String> extras = new HashMap<String, String>();
    extras.put("type", appSendMessage.getType().toString());
    extras.put("modelId",appSendMessage.getModelId().toString());
    extras.put("businessId",appSendMessage.getBusinessId().toString());
    extras.put("projectId",appSendMessage.getProjectId().toString());
    return PushPayload.newBuilder()
        .setPlatform(Platform.all())
        .setAudience(Audience.registrationId(registrationId))
        .setOptions(Options.newBuilder()
        //设置ios的APNS环境
//        .setApnsProduction(true)
            //设置第三方通道策略
//            .setThirdPartyChannelV2(thirdMap)
            .build())
//                .addCustom("notification_3rd",trd)
        .setMessage(Message.newBuilder()
            .setTitle(appSendMessage.getTitle())
            .setMsgContent(appSendMessage.getContent())
            .addExtras(extras)
            .build())
        .setNotification(Notification.newBuilder()
            .setAlert(appSendMessage.getContent())
            //设置android通知消息
            .addPlatformNotification(AndroidNotification.newBuilder()
                .setTitle(appSendMessage.getTitle())
                //设置角标自动+1
                .addCustom("badge_add_num",1)
                .addCustom("badge_class","com.example.lockboss.MainActivity")
                //设置自定义铃声，针对Android 8.0以上
//                                .setChannelId("1")
                //如果通知内容很长，可以设置大文本通知栏样式，同时style要设置为1
                .setStyle(1)
//                .setBigText("hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh")
                //设置右侧大图，只针对走极光通道
//                .setLargeIcon("https://aliosstest.woaizuji.com/image/oss//1024079842791718_5ef19fcfe9ce4c70a9b139f07da7c740.png")
                //设置厂商跳转指定界面,不设置则默认跳转到主界面
//                .addCustom("uri_activity", "com.example.lockboss.TestActivity")
//                .addCustom("uri_action", "com.example.lockboss.TestActivity")
                .addExtras(extras).build())
            //设置ios通知消息
            .addPlatformNotification(IosNotification.newBuilder()
                //设置ios标题
                .setAlert(IosAlert.newBuilder()
                    .setTitleAndBody(appSendMessage.getTitle(), null, appSendMessage.getContent())
                    .build())
                //如果要设置右侧大图，推送的时候携带 "mutable-content":true 说明是支持 iOS10 的 UNNotificationServiceExtension
                .setMutableContent(true)
                //如果不需要自定义声音，推送的时候，iOS 的 sound 值保持默认，传 default ，不要传空！
                .setSound("default")
                //设置角标自动+1
                .incrBadge(1)
//                .addExtra("type", "extra_value")
                .addExtras(extras)
                .build())
            .build())
//                .addCustom("callback", callback)
        .build();
  }

  /**
   * 设置第三方通道策略
   *     distribution 为字符串类型，取值不能为空字符串，只能是"ospush"、"jpush"、"secondary_push"。
   *     值为 ospush 表示推送强制走厂商通道下发；
   *     值为 jpush 表示推送强制走极光通道下发；
   *     值为 secondary_push 表示推送优先走极光，极光不在线再走厂商，厂商作为辅助；【建议此种方式】
   *     options.third_party_channel 的 key 只支持 xiaomi、huawei、meizu、oppo、vivo、fcm；
   */
  private static void setThirdPartyChannel(Map<String, JsonObject> thirdMap) {
    JsonObject ospushJsonObj = new JsonObject();
    ospushJsonObj.addProperty("distribution", "ospush");
    JsonObject jpushJsonObj = new JsonObject();
    jpushJsonObj.addProperty("distribution", "jpush");
    JsonObject secpushJsonObj = new JsonObject();
    secpushJsonObj.addProperty("distribution", "secondary_push");

    thirdMap.put("huawei", ospushJsonObj);
    thirdMap.put("xiaomi", ospushJsonObj);
    thirdMap.put("meizu", secpushJsonObj);
    thirdMap.put("fcm", ospushJsonObj);

  }

//  public void pushMessageToPhone(String id,Integer modelId,Integer type,String userId,String title,String content){
//    try {
//      LinkappUser linkappUser = userService.get(Long.parseLong(userId));
//      if(null == linkappUser){
//        log.info("pushMessageToPhone 用户id = {} 极光推送失败 原因：找不到用户",userId);
//        return;
//      }
//      if(StringUtils.isEmpty(linkappUser.getPhone())){
//        log.info("pushMessageToPhone 用户id = {} 极光推送失败 原因：缺少手机号",userId);
//        return;
//      }
//      AppSendMessage appSendMessage = new AppSendMessage();
//      appSendMessage.setBusinessId(id);
//      appSendMessage.setContent(content);
//      appSendMessage.setType(type);
//      appSendMessage.setModelId(modelId);
//      appSendMessage.setPhone(linkappUser.getPhone());
//      appSendMessage.setTenantId(linkappUser.getTenantId());
//      appSendMessage.setTitle(title);
//      this.sendAppMessage(appSendMessage);
//    } catch (Exception e){
//      log.error("pushMessageToPhone 用户id = {} 极光推送失败 原因：{}",userId,e.getMessage());
//    }
//
//  }
//
//  @Autowired
//  private WarningNotifierService warningNotifierService;
//
//  public void sendAppWarning(String id,Integer warningType,String msgContent,String tenantId){
//    List<String> userIds = warningNotifierService.findNotifiersByWarningTypesAndTenantId(warningType,tenantId);
//    if(CollectionUtil.isNotEmpty(userIds)&&StringUtils.isNotEmpty(msgContent)){
//      userIds.forEach(p->pushMessageToPhone(id, warningType, type.WARNING, p ,"劳务异常预警", msgContent));
//
//    }
//  }


}
